﻿Imports System.Collections.ObjectModel
Imports System.IO

Class MainWindow

    Public Property Tags As New ObservableCollection(Of Taggable)


    Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        If Not String.IsNullOrWhiteSpace(My.Settings.LastFormula) Then
            tbFormula.Text = My.Settings.LastFormula
        End If
    End Sub

    Private Sub btPickFiles_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim ofd = New Microsoft.Win32.OpenFileDialog()
        ofd.Filter = "Supported Files (*.mp3;*.wma;*.m4a)|*.mp3;*.wma;*.m4a"
        ofd.Multiselect = True

        If Not String.IsNullOrWhiteSpace(My.Settings.LastDirectory) Then
            ofd.InitialDirectory = My.Settings.LastDirectory
        End If

        Dim result = ofd.ShowDialog()
        If (result.HasValue AndAlso result.Value = True) Then
            loadFiles(ofd.FileNames)
        End If
    End Sub

    Private Sub loadFiles(ByVal fileNames As String())
        My.Settings.LastDirectory = fileNames(0).Substring(0, fileNames(0).LastIndexOf("\"))
        My.Settings.Save()

        Tags.Clear()
        For Each f In fileNames
            Dim t As New Taggable
            t.Filepath = f
            Tags.Add(t)
            t.LoadTags()
        Next
    End Sub

    Private Sub btCompute_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        ComputeTags()
    End Sub

    Private Function ComputeTags() As Boolean
        Dim clip = tbInput.Text
        Dim items = clip.Split({vbCrLf}, StringSplitOptions.RemoveEmptyEntries)

        If items.Count = 0 Then
            MessageBox.Show("No files loaded!", "Error", MessageBoxButton.OK, MessageBoxImage.Warning)
            Return False
        End If

        Dim parsedItems As New List(Of String())
        Dim formula = tbFormula.Text

        My.Settings.LastFormula = formula
        My.Settings.Save()

        Try
            Dim splitformula = Text.RegularExpressions.Regex.Replace(formula, "\%[^%]+\%", "§").Split({CChar("§")}, StringSplitOptions.RemoveEmptyEntries)
            Dim matches = Text.RegularExpressions.Regex.Matches(formula, "\%[^%]+\%")
            Dim fields As New List(Of String)

            For i As Integer = 0 To matches.Count - 1
                Dim match = matches.Item(i)
                fields.Add(match.Value)
            Next

            For Each item In items
                For Each f In splitformula
                    item = item.Replace(f, "§")
                Next
                parsedItems.Add(item.Split({"§"}, StringSplitOptions.RemoveEmptyEntries))
            Next

            WriteTags(fields, parsedItems)
            Return True
        Catch ex As Exception
            Return False
        End Try
       
    End Function

    Private Sub WriteTags(ByVal fields As IEnumerable(Of String), ByVal values As IEnumerable(Of String()))
        For t = 0 To Math.Min(Tags.Count - 1, values.Count - 1)
            Tags(t).LoadTags()

            'Pasted data
            If (values.Count > 0) Then
                Dim item = values(t)
                For i = 0 To item.Count - 1
                    Dim field = fields(i)
                    Select Case field
                        Case "%artist%"
                            Tags(t).Artist = item(i)
                        Case "%album%"
                            Tags(t).Album = item(i)
                        Case "%track%"
                            Tags(t).Track = item(i)
                        Case "%title%"
                            Tags(t).Title = item(i)
                        Case "%year%"
                            Tags(t).Year = item(i)
                    End Select
                Next
            End If

            'Static tags
            If (cbArtist.IsChecked AndAlso Not String.IsNullOrWhiteSpace(tbArtist.Text)) Then
                Tags(t).Artist = tbArtist.Text
            End If
            If (cbAlbum.IsChecked AndAlso Not String.IsNullOrWhiteSpace(tbAlbum.Text)) Then
                Tags(t).Album = tbAlbum.Text
            End If
            If (cbYear.IsChecked AndAlso Not String.IsNullOrWhiteSpace(tbYear.Text)) Then
                Tags(t).Year = tbYear.Text
            End If


            Tags(t).Notify()
        Next

    End Sub

    Private Sub btSaveTags_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        For Each item In Tags
            item.WriteTags()
            item.LoadTags()
            item.Notify()
        Next

        MessageBox.Show("Tags saved!", "Complete", MessageBoxButton.OK, MessageBoxImage.Information)
    End Sub

    Private Sub Grid_Drop(ByVal sender As System.Object, ByVal e As System.Windows.DragEventArgs)
        If e.Data.GetDataPresent(DataFormats.FileDrop) Then
            Dim files As String() = (From d In CType(e.Data.GetData(DataFormats.FileDrop), String()) Select d Where (d.ToLower.EndsWith(".mp3") OrElse d.ToLower.EndsWith(".wma") OrElse d.ToLower.EndsWith(".m4a")) Order By d).ToArray
            loadFiles(files)
        End If
    End Sub

    Private Sub btFormulaComponent_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim component = DirectCast(DirectCast(sender, Button).Content, String)
        If String.IsNullOrEmpty(tbFormula.SelectedText) Then
            Dim caretpos = tbFormula.CaretIndex
            tbFormula.Text = tbFormula.Text.Insert(caretpos, component)
            tbFormula.CaretIndex = caretpos + component.Length
        Else
            tbFormula.SelectedText = component
        End If
        tbFormula.Focus()
    End Sub
End Class
